package com.whoimi.common.jdbc;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Usage @Query(value = "",resultSetExtractorClass = ResultListMap.class)
 *  jdbc查询工具类
 * @author whoimi
 * @since 2025-08-01
 **/

public class ResultListMap implements ResultSetExtractor<List<Map<String, Object>>> {
    @Override
    public List<Map<String, Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {
        List<Map<String, Object>> results = new ArrayList<>();
        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        int colCount = resultSetMetaData.getColumnCount();
        while (rs.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 1; i <= colCount; i++) {
//                String columnName = resultSetMetaData.getColumnName(i);
                String columnLabel = resultSetMetaData.getColumnLabel(i);
                map.put(columnLabel, rs.getString(columnLabel));
            }
            results.add(map);
        }
        return results;
    }
}